import { myRequest } from "@/utils/request"
import { userManager } from "@/utils/user"
import {ElMessage} from 'element-plus'

const validityPeriod=[
  {
    item_id: '0063ad4f-d040-48c1-b3ca-bc1f338c1796',
    period: 7,
    name:'翻倍卡'
  },
  {
    item_id: '00670f04-5051-4aaa-a165-091ead954d09',
    period: 14,
    name:'翻倍卡'
  },
  {
    item_id: '0073d15b-8263-49a8-8ede-201fba7dff57',
    period: 1,
    name:'翻倍卡'
  },
  {
    item_id: '01e609cb-0f47-4982-9f5b-5236c46d2ec0',
    period: 30,
    name:'翻倍卡'
  },
  {
    item_id: '00991174-410c-4570-ba26-2035e56247d5',
    period: 1,
    name:'七五折卡'
  },
  {
    item_id: '0099bdd7-5c50-4f2a-8207-01c2c77802dd',
    period: 1,
    name:'五折卡'
  },
]


export var shopItemService={
    getShopItemInfo:function(success){
        myRequest.request({
            url:'shop_items',
            method:'GET',
            data:null,
            success:success
        })
    },
    getShopItemHistory:function(user_id,success){
        myRequest.request({
            url:'item_exchanges/'+user_id,
            method:'GET',
            data:null,
            success:success
        })
    },
    addShopItem:function(shopItem,success){
        myRequest.formRequest({
            url:'shop_items',
            method:'POST',
            data:shopItem,
            success:success
        })

    },
    decreaseShopItem:function(shopItemId,num,success)
    {
        myRequest.request({
            url:'shop_items/'+shopItemId,
            method:'DELETE',
            data:{
                "num":num,
                "user_id":userManager.getUserId()

            },
            success:success
        })

    },
    updateCredit: function(credit) {
    // 首先获取当前用户的购物历史记录
    const userId = userManager.getUserId();
    let adjustedCredit = credit;
    
    // 这里需要同步获取用户的购物记录，实际项目中可能需要异步处理
    // 假设我们已经获取到了shopHistory数据

    const shopHistory =this.getLocalHistoryShopItem(); // 这里应该从服务获取实际数据
    // this.getShopItemHistory(userId,(res)=>{
    //     shopHistory=res.data
    // })
    // 检查当前是否有生效的虚拟卡
       console.log(typeof(shopHistory))
    const activeCards = shopHistory.filter(item => 
        item.type === 0 && // 虚拟卡类型
        !item.isEffective && // 已使用
        new Date(item.date) <= new Date() && // 已开始
        new Date(new Date(item.date).getTime() + (validityPeriod.find(v => v.item_id === item.item_id)?.period || 0) * 24 * 60 * 60 * 1000) >= new Date() // 未过期
    );

    var isDoubled = false;
    var isHalfed = false;
    var isSevenFive = false;
    
    // 处理每种卡的效果
    activeCards.forEach(card => {
        const cardInfo = validityPeriod.find(v => v.item_id === card.item_id);
        if (!cardInfo) return;
        
        if (cardInfo.name === '翻倍卡' && credit > 0) {
            if(!isDoubled)
            {
                isDoubled=true;
                  // 学分翻倍（仅对正数学分）
                adjustedCredit =credit* 2;
                ElMessage({
                message: '您的翻倍卡已生效，获取'+adjustedCredit+'学分！',
                type: 'success'
                })
            }
           

        } else if (cardInfo.name === '五折卡' && credit < 0) {
            if(!isHalfed)
            {
                isHalfed=true;
                 // 五折卡（仅对负数学分）
            adjustedCredit =credit* 0.5;
            ElMessage({
                message: '您的打折卡已生效，花费'+adjustedCredit+'学分！',
                type: 'success'
              })

            }
           
        } else if (cardInfo.name === '七五折卡' && credit < 0) {
            if(!isSevenFive)
            {
                isSevenFive=true;
                // 七五折卡（仅对负数学分）
            adjustedCredit = credit* 0.75;
            ElMessage({
                message: '您的打折卡已生效，花费'+adjustedCredit+'学分！',
                type: 'success'
              })
            }
            
        }
    });
    return adjustedCredit;
    },
    updateCreditNoMsg: function(credit) {


    // 首先获取当前用户的购物历史记录
    let adjustedCredit = credit;
    
    const shopHistory =this.getLocalHistoryShopItem(); // 这里应该从服务获取实际数据
    // this.getShopItemHistory(userId,(res)=>{
    //     shopHistory=res.data
    // })
    // 检查当前是否有生效的虚拟卡
     //  console.log(typeof(shopHistory))
    const activeCards = shopHistory.filter(item => 
        item.type === 0 && // 虚拟卡类型
        !item.isEffective && // 已使用
        new Date(item.date) <= new Date() && // 已开始
        new Date(new Date(item.date).getTime() + (validityPeriod.find(v => v.item_id === item.item_id)?.period || 0) * 24 * 60 * 60 * 1000) >= new Date() // 未过期
    );
    
    // 处理每种卡的效果
    activeCards.forEach(card => {
        const cardInfo = validityPeriod.find(v => v.item_id === card.item_id);
        if (!cardInfo) return;
        
        if (cardInfo.name === '翻倍卡' && credit > 0) {
            // 学分翻倍（仅对正数学分）
            adjustedCredit =credit* 2;
            

        } else if (cardInfo.name === '五折卡' && credit < 0) {
            // 五折卡（仅对负数学分）
            adjustedCredit =credit* 0.5;
            
        } else if (cardInfo.name === '七五折卡' && credit < 0) {
            // 七五折卡（仅对负数学分）
            adjustedCredit = credit* 0.75;
        }
    });
    return adjustedCredit;
    },
    getShopItems:function(success){
        myRequest.request({
            url:'shop_items',
            method:'GET',
            data:null,
            success:success
        })
    },
    useVirtualCard:function(shopItemId,success){
        myRequest.request({
            url:'item_exchanges/'+shopItemId,
            method:'PUT',
            data:{
                "num":1,
                "user_id":userManager.getUserId()
            },
            success:success
        })
    },
    confirmReceipt:function(shopItemId,success){
        myRequest.request({
            url:'item_exchanges/'+shopItemId,
            method:'PUT',
            data:{
                "num":1,
                "user_id":userManager.getUserId()
            },
            success:success
        })
    },
    setLocalHistoryShopItem:function(shopItem){
        localStorage.setItem('historyShopItem',JSON.stringify(shopItem))
    },
    getLocalHistoryShopItem:function(){
        if(localStorage.getItem('historyShopItem')==null)
        {
            return []
        }
        return  JSON.parse(localStorage.getItem('historyShopItem'))
    },
    useFrame:function(item_id,success){
        myRequest.request({
            url:'item_exchanges/'+item_id,
            method:'PUT',
            data:{
                "num":1,
                "user_id":userManager.getUserId()
            },
            success:success
        })
    }
   
}